# -*- coding: utf-8 -*-
"""
@Time : 2023/7/28 14:03
@Author : ChenXiaoliang
@Email : middlegod@sina.com
@File : add_book.py
"""
import sys
import datetime
from flask_restful import Resource, reqparse

from service.mysql_connect import MySQLConnected
from service.config_import import load_yaml

sys.path.append('..')

parser = reqparse.RequestParser()
parser.add_argument('book_name', type=str, help="参数book_name不能为空", required=True)
parser.add_argument('book_code', type=str, help="参数book_code不能为空", required=True)
parser.add_argument('book_author', type=str, help="参数book_author不能为空", required=True)


class AddBook(Resource):
    def post(self):
        args = parser.parse_args()
        book_name = args.get('book_name').strip()
        book_code = args.get('book_code').strip()
        book_author = args.get('book_author').strip()
        yaml_config_path = "config_info.yaml"
        params = load_yaml(yaml_config_path)
        dbinfo = params['databases']['library_db_info']
        db = params['databases']['library_db_name']
        connected = MySQLConnected(dbinfo)
        # print(connected.con)
        # print(connected.cur)
        # print("insert into test_roast.roast (val) values ('" + roast + "');")
        # 数据库名：test_library 数据表名：books
        # 数据库DDL
        # CREATE TABLE `books`(
        #     `id` int NOT NULL AUTO_INCREMENT,
        #     `name` varchar(150) NOT NULL COMMENT '书名',
        #     `code` varchar(150) NOT NULL COMMENT '书编码',
        #     `author` varchar(50) NOT NULL COMMENT '书作者',
        #     `status` int NOT NULL DEFAULT '1' COMMENT '书借用状态,1-可借,0-不可借',
        #     `valid` int NOT NULL DEFAULT '1' COMMENT '书籍状态,1-有效,0-无效',
        #     `creation` varchar(50) DEFAULT NULL COMMENT '创建时间,书籍录入到数据库的时间',
        #     PRIMARY KEY (`id`)
        # ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
        now = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
        sql = "insert into " + db + ".books(name,code,author,status,valid,creation) values (%s,%s,%s,1,1," + now + ");"
        connected.cur.execute(sql, (book_name, book_code, book_author))
        # connected.cur.execute(("insert into " + db + ".roast (val, ts) values ('" + roast + "',%s);"), now)
        # 提交到数据库
        connected.con.commit()
        # 关闭游标
        connected.cur.close()
        # 关闭数据库
        connected.con.close()

        return {'content': book_name + "添加成功~", 'result': 'success'}
